package com.inno.subject.domain.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Sean
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {
    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() + 1;
    private static final int MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2 + 1;
    private static final int WORK_QUEUE_SIZE = 1000;
    private static final int KEEP_ALIVE_TIME = 60;
    @Bean("subjectExecutor")
    public ThreadPoolTaskExecutor executor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(WORK_QUEUE_SIZE);
        executor.setThreadNamePrefix("subject-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 拒绝策略  当任务拒绝后 把任务回退给提交的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        executor.initialize();
        return executor;
    }

}
